# -*-tcl-*-

# -- Aliases:

alias  .      changes
alias  d      diff
alias  ,      ui
alias  log    timeline
alias  heads  leaves;       # for hg refugees
alias log      timeline
alias history {timeline -n 100}
alias live  {set autosync on}
alias local {set autosync off}


# -- Filters:

filter status {changes status timeline add rm addremove} {
    lassign [split [string trim $line]] status
    switch $status {
        MERGED_WITH { coloured purple $line }
        ADDED       { coloured  green $line }
        EDITED      { coloured   cyan $line }
        DELETED     { coloured    red $line }
        default     {             set  line }
    }
}

filter log_entry {leaves tim:timeline} {
    if {[regexp "^=== .* ===" $line]} {
        coloured blue $line
    } else {
        regsub -all {\[[A-Fa-f0-9]+\]} $line [coloured yellow &]
    }
}



# Filter on alias `d' instead of `diff' so that output can be
# redirected to create patch files.
filter diff {d} {
    switch -regexp $line {
        {^-}    { coloured    red $line }
        {^\+}   { coloured  green $line }
        {^@@}   { coloured yellow $line }
        default {             set  line }
    }
}


filter branch {br:branch} {
    switch -regexp $line {
        {^\*}   { coloured yellow $line }
        default {             set  line }
    }
}

# fsl purge
# Purge all files flagged as "MISSING".
alias capture_changes changes

filter captured_changes {capture_changes} {
    variable captured
    lappend captured $line
    return {}
}

interceptor cr:create {
    global tcl_platform

    set repodir [file join [file normalize ~] Repositories]
    set reponame [file join $repodir [file tail [pwd].fossil]]
    set skeleton [file join $repodir skeleton.fossil]

    set user $tcl_platform(user)
    set password [lindex $params 1]

    fossil new $reponame --template $skeleton
    fossil open $reponame

    if {$password != ""} {
        fossil user password $user $password
    }

    fossil branch new development trunk
    fossil update development

    return {}
}

interceptor purge {
    variable captured {}
    fossil capture_changes
    foreach line $captured {
        if [string match MISSING* $line] {
            regsub ^MISSING $line {} file
            fossil rm [string trim $file]
        }
    }
    return {}
}
proc fixKicadDates {} {
  set fix_pro_cmd [string trim {
    sh -c {find . -name "*.pro" -print0 | xargs -0 gsed -E -i.bkp 's/update=.*/update=Date/'}
  }]
  set fix_sch_cmd [string trim {
    sh -c {find . -name "*.sch" -print0 | xargs -0 gsed -E -i 's/#(PWR|FLG)[0-9]+/#\1?/'}
  }]

  exec {*}$fix_pro_cmd
  exec {*}$fix_sch_cmd
}

interceptor kici {
  switch [catch fixKicadDates err] {
    0 { fossil commit {*}[lrange $params 1 end] }
    1 { puts stderr $err }
  }
  return {}
}
